package com.tang.common.entity;


import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

public class PageResult<T> {
    private Integer pageNo = 1;
    private Integer pageSize = 20;
    private Integer total = 0;
    private Integer totalPages = 0;
    private List<T> result = Collections.emptyList();
    private Integer start = 1;
    private Integer end = 0;

    public void setRecords(List<T> result) {
        this.result = result;
    }

    public void setTotal(Integer total) {
        this.total = total;
        if (this.pageSize > 0) {
            this.totalPages = (total / pageSize) + (total % pageSize == 0 ? 0 : 1);
        } else {
            this.totalPages = 0;
        }
        this.start = (this.pageSize > 0 ? (this.pageNo - 1) * this.pageSize : 0) + 1;
        this.end = (this.start - 1 + this.pageSize * (this.pageNo > 0 ? 1 : 0));
    }

    public <M> PageResult<M> convert(Function<T, M> function) {
        PageResult<M> copied = copy();
        if (Objects.isNull(result) || result.isEmpty()) {
            copied.setResult(Collections.emptyList());
            return copied;
        }
        List<M> collect = result.stream().map(function).collect(Collectors.toList());
        copied.setResult(collect);
        return copied;
    }

    private <M> PageResult<M> copy() {
        PageResult<M> newOne = new PageResult<>();
        newOne.setPageNo(pageNo);
        newOne.setPageSize(pageSize);
        newOne.setTotal(total);
        newOne.setTotalPages(totalPages);
        newOne.setStart(start);
        newOne.setEnd(end);
        return newOne;
    }

    public Integer getPageNo() {
        return pageNo;
    }

    public void setPageNo(Integer pageNo) {
        this.pageNo = pageNo;
    }

    public Integer getPageSize() {
        return pageSize;
    }

    public void setPageSize(Integer pageSize) {
        this.pageSize = pageSize;
    }

    public Integer getTotal() {
        return total;
    }

    public Integer getTotalPages() {
        return totalPages;
    }

    public void setTotalPages(Integer totalPages) {
        this.totalPages = totalPages;
    }

    public List<T> getResult() {
        return result;
    }

    public void setResult(List<T> result) {
        this.result = result;
    }

    public Integer getStart() {
        return start;
    }

    public void setStart(Integer start) {
        this.start = start;
    }

    public Integer getEnd() {
        return end;
    }

    public void setEnd(Integer end) {
        this.end = end;
    }
}
